/*
 * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * o Neither the name of Freescale Semiconductor, Inc. nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "connector_thread.h"
#include "connector_common.h"

extern ConnectorConfigure g_connectorConfig;
static bool g_kabsSendEnable = false;

/*FUNCTION*********************************************************************
 *
 * Function Name : getKABSUID
 * Description   : Connect to server up to 5 times and request for KABS's UID.
 * Then save it in g_connectorConfig.kabsUID
 *END*************************************************************************/
bool getKABSIP(char *serverIP, uint16_t portRequest, char *targetBoard, char *kabsIP)
{
    const uint32_t max_try = 5;
    uint32_t try_count = 0;
    int32_t i_result = 0;
    sockaddr_in client_addr;

    client_addr.sin_family = AF_INET;
    client_addr.sin_addr.s_addr = inet_addr(serverIP);
    client_addr.sin_port = htons(portRequest);

    while (try_count < max_try)
    {
        SOCKET req_socket;
        req_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

        i_result = connect(req_socket, (SOCKADDR *) & client_addr, sizeof (client_addr));

        if (i_result != 0) /* connect failed */
        {
            try_count++;
            closesocket(req_socket);
        }
        else
        {

            /* Connect successfully, request to get uid */
            send(req_socket,
                 targetBoard,
                 strlen(targetBoard) + 1, 0);

            /* Wait IP info */
            i_result = recv(req_socket,
                            kabsIP,
                            BUFFER_LEN,
                            0);

            closesocket(req_socket);

            /* Unvalid IP */
            if (i_result < 7)
            {
                return false;
            }
            break;
        }
    }
    if (try_count >= max_try)
        return false;

    return true;
}

/*FUNCTION*********************************************************************
 *
 * Function Name : getOrder
 * Description   : Get order from stdin. Return at any input char of '\n', '\r'
 * or input is larger than buffer_sz.
 *END*************************************************************************/
void getOrder(char *buffer, uint32_t buffer_sz)
{
    uint32_t char_read = 0;
    while (char_read < buffer_sz - 1)
    {
        char c = (char)getchar();
        if (char_read == 0 && isalnum(c) == 0 && c != '$')
            continue;
        if (c == '\n' || c == '\r')
            break;
        buffer[char_read] = c;
        char_read++;
    }
    buffer[char_read] = '\0'; /* Add NULL to make a string */
}

/*FUNCTION*********************************************************************
 *
 * Function Name : sendOrderToKABS
 * Description   : Read from STDIN(blocked), then request Server for related
 * KABS IP, send all messages from STDIN to KABS by TCPIP. Use port
 * g_connectorConfig.portComm for communication.
 *END*************************************************************************/
int32_t sendOrderToKABS()
{
    char order[BUFFER_LEN];

    /* Get KABS IP first to ensure order send */
    char kabsIP[BUFFER_LEN];
    bool ip_get_res = false;

    memset(kabsIP, 0, BUFFER_LEN);
    ip_get_res = getKABSIP(g_connectorConfig.serverIP, g_connectorConfig.portRequest,
                         g_connectorConfig.targetBoard,
                         kabsIP
                         );
    if (ip_get_res)
    {
        int32_t connect_result = 0;
        int32_t send_result = 1;
        sockaddr_in client_addr;

        client_addr.sin_family = AF_INET;
        client_addr.sin_addr.s_addr = inet_addr(kabsIP);
        client_addr.sin_port = htons(g_connectorConfig.portComm);

        /* Create a SOCKET for sending order */
        SOCKET comm_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

        g_board_send_log << tstamp << "Try to connect KABS[" << kabsIP <<"].\n";
        connect_result = connect(comm_socket, (SOCKADDR *) & client_addr, sizeof (client_addr));

        /*
         * Connect KABS successfully.
         * Keep this connection alive until KABS cuts off.
         */
        if (connect_result == 0)
        {
            g_board_send_log << tstamp << "Connected to KABS[" << kabsIP << "].\n";
            /* Configure socket */
            int32_t set_res;
            /* Send data in single package */
            BOOL opt_val = TRUE;
            int32_t opt_len = sizeof(opt_val);
            set_res = setsockopt(comm_socket, IPPROTO_TCP, TCP_NODELAY, \
                       (const char *) &opt_val, \
                       opt_len);
            if (set_res == SOCKET_ERROR)
            {
                printf("setsockopt for TCP_NODELAY failed with error: %u\n",
                       WSAGetLastError());
                return -1;
            }
            /* Create thread for feedback from KABS */
            DWORD threadID;
            HANDLE h = CreateThread(NULL, 0, \
                        (LPTHREAD_START_ROUTINE)recvFdbkFromKABS, \
                        (LPVOID) &comm_socket, 0, &threadID);
            /* Hold for retransmission until send() fails */
            while (true)
            {
                /* Wait for Dapeng's order */
                memset(order, 0, BUFFER_LEN);

                getOrder(order, BUFFER_LEN);
                if (strlen(order) == 0)
                    continue;

                g_board_send_log << tstamp << "From Dapeng: Order: "<<  order<< ".\n";
                /* For auto-test */
                if (strcmp(order, "over") == 0)
                {
                    printf("Success.\n");
                    TerminateThread(h, threadID);
                    return 0;
                }

                /* Hold until KABS connect */
                while (g_kabsSendEnable == false)
                {
                    Sleep(500);
                }
                /* Connect successfully, retransfer order */

                send_result = send(comm_socket, order, BUFFER_LEN - 1, 0);

                if (send_result > 0)
                {
                    g_board_send_log << tstamp <<"Send to KABS["<<kabsIP<<"]: "<<order<<".\n";
                }
                /* Fail to send, exit */
                else
                {
                    g_board_send_log << tstamp << "Cannot send to KABS["<<kabsIP<<"]: "<<order<<".\n";

                    closesocket(comm_socket);

                    return -1;
                }
            }
        }
        /* Fail to connect to KABS, exit */
        else
        {
            g_board_send_log << tstamp <<"Failed to connect KABS[" << kabsIP << "].\n";
            closesocket(comm_socket);

            return -1;
        }

    }
    else
    {
        printf("Failed to get KABS IP.\n");

        g_board_send_log << tstamp <<"Failed to get KABS IP.\n";
        return -1;
    }

    return 0;
}

/*FUNCTION*********************************************************************
 *
 * Function Name : recvFdbkFromKABS
 * Description   : Block waiting for messages from KABS and send all messages
 * to DP by STDOUT. Use port g_connectorConfig.portComm for communication.
 * Function will block until it accepts a connection from KABS, then continues
 * to block until it receives a message from KABS and send it to DP by Stdout.
 * NOTE: Whenever KABS needs to send a message, it's necessaray to create a new
 * connection and close it after message sent. Connector NEVER keeps a
 * long-live connection.
 *END*************************************************************************/
DWORD WINAPI recvFdbkFromKABS(LPVOID pM)
{
    SOCKET comm_socket = *((SOCKET *) pM);
    char data[BUFFER_LEN];
    char buf[LOG_MAX];

    sockaddr_in client_addr;
    uint32_t recvNum = 0;

    g_kabsSendEnable = false;

    if (INVALID_SOCKET != comm_socket)
    {
        g_kabsSendEnable = true;

        while (true)
        {
            /* Hold to recv */
            memset(data, 0, BUFFER_LEN); /* Clear buffer */
            recvNum = recv(comm_socket, data, BUFFER_LEN-1, 0);
            /* receive successfully */
            if (recvNum > 0)
            {
                while (recvNum != BUFFER_LEN - 1)
                {
                    recvNum += recv(comm_socket, data + recvNum, BUFFER_LEN-1-recvNum, 0);
                }
                data[recvNum] = '\0';
                /* Send to DP */
                g_board_recv_log << data;
            }
            else /* socket occurs error, thread exit */
            {
                shutdown(comm_socket, SD_RECEIVE);

                g_board_recv_log << "Recv() failed[Error Code:"<<WSAGetLastError()<<" ].\n";

                closesocket(comm_socket);

                return -1;
            }
        }
    }
    /* Close socket */
    closesocket(comm_socket);

    return 0;
}
/* EOF */
